#include "userdao.h"
#include <QCryptographicHash>

UserDao::UserDao(Database *db) : m_db(db) {}

bool UserDao::authenticateUser(const QString &username, const QString &password, int &role_id)
{
    // 对密码进行SHA256加密
    QByteArray passwordHash = QCryptographicHash::hash(
        password.toUtf8(), QCryptographicHash::Sha256).toHex();

    // 修复字段名：role_id 而不是 role
    QString query = "SELECT role_id FROM user WHERE username = ? AND password_hash = ?";
    QVector<QMap<QString, QVariant>> result = m_db->query(query, {username, QString(passwordHash)});

    if (!result.isEmpty()) {
        // 修复：获取正确的role_id字段值
        role_id = result[0]["role_id"].toInt();
        return true;
    }
    return false;
}

bool UserDao::isUsernameExist(const QString &username)
{
    QString query = "SELECT user_id FROM user WHERE username = ?";
    QVector<QMap<QString, QVariant>> result = m_db->query(query, {username});
    return !result.isEmpty();
}

bool UserDao::registerUser(const QString &username, const QString &password,
                          const QString &real_name, int role_id)
{
    // 对密码进行SHA256加密
    QByteArray passwordHash = QCryptographicHash::hash(
        password.toUtf8(), QCryptographicHash::Sha256).toHex();

    // 修复1：使用正确的字段名role_id
    // 修复2：添加必需的real_name字段
    QString query = "INSERT INTO user (username, password_hash, role_id, real_name) VALUES (?, ?, ?, ?)";

    // 执行插入操作
    return m_db->execute(query, {username, QString(passwordHash), role_id, real_name});
}
